// src/handlers/weiboHandler.js
const puppeteer = require("puppeteer-extra");
const StealthPlugin = require("puppeteer-extra-plugin-stealth");
puppeteer.use(StealthPlugin());
const axios = require("axios");
const cheerio = require("cheerio");
const md5 = require("md5");
const dayjs = require("dayjs");
const logger = require("../../utils/logger");
const headers = {
  Cookie: process.env.WEIBO_HEADERS_COOKIE,
  "User-Agent": process.env.WEIBO_HEADERS_USER_AGENT,
};
const userDataDir = process.env.WEB_CONFIG_USER_DATA_DIR;
const executablePath = process.env.WEB_CONFIG_EXECUTABLE_PATH;
const notification = require("../../utils/notification");
const {
  sendWechatMessage,
  // publishCallback,
  convertToStandardFormat,
} = require("../../utils");
const fs = require("fs");
const path = require("path");
const { promisify } = require("util");
const stream = require("stream");
const pipeline = promisify(stream.pipeline);

exports.handleCommand = async (command, params, taskId) => {
  switch (command) {
    case "getUserInfo":
      return await searchUser(params?.keyword);
    case "search":
      return await searchWeibo(params?.keyword);
    case "getArticlesInfo":
      const data = await getArticlesInfo(params);
      console.log('<<<<<<<<<<---------------->>>>>>', data)
      return {
        data,
      };
    case "publish":
      try {
        const result = await publish(params);
        if (result.success) {
          // await publishCallback(
          //   params.post_id,
          //   3,
          //   "发布成功",
          //   taskId,
          //   result.id
          // );
          return {
            data: [
              {
                ...result,
              },
            ],
          };
        } else {
          throw new Error(result.message || "发布失败");
        }
      } catch (error) {
        logger.error(`发布微博时发生错误: ${error.message}`);
        // await publishCallback(params.post_id, 4, error.message, taskId, "");
        return {
          data: [
            {
              success: false,
              message: error.message,
            },
          ],
        };
      }
    default:
      throw new Error("NOT_SUPPORT_COMMAND");
  }
};
//----------------------------------------获取作品信息开始----------------------------------------------------
async function getArticlesInfo(params) {
  const browser = await puppeteer.launch({
    // headless: "new",
    headless: false,
    userDataDir,
    executablePath,
    defaultViewport: null,
    args: [
      "--no-sandbox",
      "--disable-setuid-sandbox",
      "--disable-features=site-per-process",
      "--start-maximized",
      // "--auto-open-devtools-for-tabs",
    ],
    ignoreHTTPSErrors: true,
  });
  const page = await browser.newPage();
  //根据屏幕尺寸设置页面大小
  const { width, height } = await page.evaluate(() => {
    return {
      width: document.documentElement.clientWidth,
      height: document.documentElement.clientHeight,
    };
  });
  logger.info(
    "浏览器窗口实际大小: " + JSON.stringify({ width, height }, null, 2)
  );

  await page.setViewport({ width, height });
  try {
    await page.goto("https://weibo.com/manage/manage", {
      waitUntil: "networkidle2",
    });
    if (await isNotLogin(page)) {
      logger.info("未登录");
      await notification(
        "微博",
        `${process.env.NODE_ENV}环境下的微博未登录`,
        "请扫码登录"
      );

      // 显示二维码
      await showQRCode(page);

      // 等待用户登录
      await waitForUserLogin(page);

      await notification(
        "微博",
        `${process.env.NODE_ENV}环境下的微博登录成功`,
        "登录成功"
      );
    }

    logger.info("已登录");
    await page.goto("https://dss.sc.weibo.com/pc/index", {
      waitUntil: "networkidle2",
    });
    //获取粉丝数
    const fansCount = await getFansCount(page);
    logger.info(`粉丝数: ${fansCount}`);
    //获取博文分析数据
    const articles = await getArticles(page, params, fansCount);
    return articles;
  } catch (error) {
    logger.error(`发生错误: ${JSON.stringify(error, null, 2)}`);
    return [];
  } finally {
    await browser.close();
  }
}
//判断是否登录
async function isNotLogin(page) {
  // 找到button按钮,内容含有立即登录的按钮
  const buttonExists = await page.evaluate(() => {
    const buttons = Array.from(document.querySelectorAll("button"));
    return buttons.some((button) => button.textContent.trim() === "立即登录");
  });
  const loginQrCodeExists = await page.evaluate(() => {
    const img = document.querySelector("img.w-full.h-full");
    return img ? img.src : null;
  });
  return buttonExists || loginQrCodeExists;
}
async function showQRCode(page) {
  await page.goto(
    `https://passport.weibo.com/sso/signin?entry=miniblog&source=miniblog&url=${encodeURIComponent(
      "https://me.weibo.com/data/overview"
    )}`,
    {
      waitUntil: "networkidle2",
    }
  );
  await getQrCodeBase64AndSend(page);
}
//获取二维码base64并发送
async function getQrCodeBase64AndSend(page) {
  try {
    const imgSrc = await getQRCodeImageSrc(page);

    if (!imgSrc) {
      throw new Error("无法获取二维码图片源");
    }

    try {
      const response = await axios.get(imgSrc, {
        responseType: "arraybuffer", // 将图片作为二进制数据获取
      });
      const bufferImage = Buffer.from(response.data, "binary");
      await sendQRCodeToWechat(bufferImage);
    } catch (error) {
      logger.error(`获取二维码失败: ${error.message}`);
      throw error;
    }
  } catch (error) {
    logger.error(`获取或发送二维码失败: ${error.message}`);
    throw error;
  }
}
async function getQRCodeImageSrc(page) {
  return await page.evaluate(() => {
    const img = document.querySelector("img.w-full.h-full");
    return img ? img.src : null;
  });
}
async function sendQRCodeToWechat(bufferImage) {
  logger.info(`微博登录二维码获取成功`);
  const imgBase64 = bufferImage.toString("base64");
  try {
    await sendWechatMessage({
      msgtype: "image",
      image: {
        base64: imgBase64,
        md5: md5(bufferImage),
      },
    });
    logger.info(`发送图片信息成功`);
    return true;
  } catch (error) {
    logger.error(`发送图片信息失败:${error.message}`);
  }
}
async function waitForUserLogin(page) {
  return new Promise((resolve, reject) => {
    logger.info("请在浏览器中完成登录，登录成功后脚本将自动继续...");
    const checkInterval = setInterval(async () => {
      try {
        const notLoggedIn = await isNotLogin(page);
        if (!notLoggedIn) {
          clearInterval(checkInterval);
          clearTimeout(timeoutId);
          logger.info("检测到登录成功");
          resolve();
        } else {
          const isQRCodeExpired = await checkQRCodeExpired(page);
          if (isQRCodeExpired) {
            logger.info("二维码已过期，正在刷新...");
            await refreshQRCode(page);
            await notification(
              "微博",
              `${process.env.NODE_ENV}环境下的微博二维码已过期`,
              "正在刷新"
            );
            await getQrCodeBase64AndSend(page);
          }
        }
      } catch (error) {
        logger.error(`检查登录状态时出错:${error}`);
      }
    }, 2000);

    const timeoutId = setTimeout(async () => {
      clearInterval(checkInterval);
      logger.error("登录等待超时（10分钟）");
      await notification(
        "微博",
        `${process.env.NODE_ENV}环境下的微博登录失败`,
        "等待超时"
      );
      reject(new Error("登录等待超时，请重试"));
    }, 10 * 60 * 1000);
  });
}
async function checkQRCodeExpired(page) {
  // 微博特定的二维码过期检查逻辑，刷新按钮,类名为text-brand
  return await page.evaluate(() => {
    const refreshButton = document.querySelector(".text-brand");
    if (refreshButton) {
      return true;
    }
    return false;
  });
}
async function refreshQRCode(page) {
  // 微博特定的二维码刷新逻辑
  await page.evaluate(() => {
    const refreshButton = document.querySelector(".text-brand");
    if (refreshButton) {
      refreshButton.click();
    }
  });
}
// 取粉丝数
async function getFansCount(page) {
  //跳转粉丝分析tab页
  await page.evaluate(() => {
    const tabs = document.querySelectorAll(".main-nav li");
    //找到内容为粉丝分析的tab
    const fansTab = Array.from(tabs).find((tab) =>
      tab.textContent.includes("粉丝分析")
    );
    if (fansTab) {
      fansTab.click();
    }
  });
  //拦截 https://dss.sc.weibo.com/pc/aj/chart/fans/fansTrend 请求，获取响应数据内的粉丝总数
  const response = await page.waitForResponse((response) =>
    response
      .url()
      .includes("https://dss.sc.weibo.com/pc/aj/chart/fans/fansTrend")
  );
  const data = await response.json();
  // 确保 data 和 data.data 存在
  if (data?.data?.param?.followers_count) {
    return data.data.param.followers_count;
  } else {
    logger.error("无法获取粉丝数据");
    return 0;
  }
}
//获取博文分析数据
async function getArticles(page, params, fansCount) {
  logger.info("开始获取博文分析数据");
  logger.info(`参数: ${JSON.stringify(params)}`);
  logger.info(`粉丝数: ${fansCount}`);

  //跳转博文分析tab页
  await page.evaluate(() => {
    const tabs = document.querySelectorAll(".main-nav li");
    //找到内容为博文分析的tab
    const articlesTab = Array.from(tabs).find((tab) =>
      tab.textContent.includes("博文分析")
    );
    console.log("articlesTab", articlesTab);
    if (articlesTab) {
      articlesTab.click();
    }
  });
  //根据params参数，选择对应的日期范围
  await selectDateRange(page, params);
  logger.info("选择日期范围成功");

  const results = [];
  let pageCount = 0;

  while (true) {
    pageCount++;
    logger.info(`正在获取第 ${pageCount} 页的数据...`);

    try {
      const response = await page.waitForResponse(
        (response) =>
          response
            .url()
            .includes("https://dss.sc.weibo.com/pc/aj/chart/content/weiboList"),
        { timeout: 30000 }
      );

      const data = await response.json();
      logger.info(`成功获取第 ${pageCount} 页数据`);
      if (
        data?.data?.chart?.weiboList?.list &&
        data.data.chart.weiboList.list.length > 0
      ) {
        data.data.chart.weiboList.list.forEach((item) => {
          results.push({
            content: item.text,
            id: item.midd,
            mid: item.mid,
            origin_date: item.date,
            publish_time: convertToStandardFormat(item.date),
            read_count: item.read,
            reader_count: item.readPeople,
            forward_count: item.repost,
            comment_count: item.comment,
            like_count: item.like,
            fans_count: fansCount,
          });
        });
        logger.info(
          `第 ${pageCount} 页添加了 ${data.data.chart.weiboList.list.length} 条数据`
        );
      } else {
        logger.warn(`第 ${pageCount} 页没有找到有效数据`);
      }

      if (!data.data.chart.weiboList.hasMore) {
        logger.info("没有更多数据，结束获取");
        break;
      }
      await new Promise((resolve) => setTimeout(resolve, 3000));
      // 修改这里：使用 page.evaluate 来查找和点击"下一页"按钮
      const nextButtonClicked = await page.evaluate(() => {
        const buttons = document.querySelectorAll(".load-more span");
        for (const button of buttons) {
          if (button.textContent.includes("下一页")) {
            button.click();
            return true;
          }
        }
        return false;
      });

      if (nextButtonClicked) {
        logger.info('已点击"下一页"按钮');
      } else {
        logger.warn('没有找到"下一页"按钮，结束获取');
        break;
      }
    } catch (error) {
      logger.error(`获取第 ${pageCount} 页数据时出错: ${error.message}`);
      break;
    }
  }

  logger.info(`总共获取了 ${results.length} 条数据`);
  return results;
}
//选择日期
async function selectDateRange(page, params) {
  if (params.update_type === "highFrequency") {
    //点击单条微博分析下面的，近7天选项
    // await page.evaluateHandle(() => {
    //   const tabs = document.querySelectorAll(".weibo-list li");
    //   const tab = Array.from(tabs).find((item) =>
    //     item.textContent.includes("近7天")
    //   );
    //   console.log("tab", tab);
    //   if (tab) {
    //     tab.click();
    //   }
    // });
  } else {
    await page.waitForSelector(".weibo-list");
    //点击单条微博分析下面的，近30天选项
    await page.evaluateHandle(() => {
      const tabs = document.querySelectorAll(".weibo-list li");
      console.log("tabs", tabs);
      const tab = Array.from(tabs).find((item) =>
        item.textContent.includes("近30天")
      );
      console.log("tab", tab);
      if (tab) {
        tab.click();
      }
    });
  }
}
//----------------------------------------获取作品信息结束----------------------------------------------------
// 搜索用户
const searchUser = async (keyword) => {
  if (!keyword) {
    throw new Error("KEYWORD_IS_REQURED");
  }
  const url = `https://s.weibo.com/user?q=${encodeURIComponent(
    keyword
  )}&Refer=weibo_user`;
  const response = await axios.get(url, {
    headers,
  });

  // 需要解析返回的 HTML，提取用户信息
  return parseUserResponse(response.data, keyword);
};
// 搜索微博
const searchWeibo = async (keyword) => {
  const url = `https://s.weibo.com/weibo?q=${encodeURIComponent(keyword)}`;
  const response = await axios.get(url, {
    headers,
  });
  // 需要解析返回的 HTML，提取微博内容
  return parseWeiboResponse(response.data);
};
//获取用户信息
const fetchUserProfile = async (uid) => {
  try {
    const response = await axios.get(
      `https://weibo.com/ajax/profile/info?uid=${uid}`,
      {
        headers,
      }
    );
    if (response.data.ok === 1) {
      return response.data.data.user;
    } else {
      //可能出发反爬
      throw new Error("UNAUTHORIZED");
    }
  } catch (error) {
    throw error;
  }
};
//解析用户信息
const parseUserResponse = async (html, keyword) => {
  const $ = cheerio.load(html);
  const firstCardWrap = $(".card:first"); // 选取第一个 .card 元素
  if (!firstCardWrap || firstCardWrap.length === 0) {
    //触发反扒机制，抛出个错误类型
    throw new Error("UNAUTHORIZED");
  }

  const userName = firstCardWrap.find(".name").text();
  const uid = firstCardWrap.find(".woo-button-main").attr("uid");

  if (!uid) {
    throw new Error("USER_DOES_NOT_EXIST");
  }
  if (!keyword) {
    throw new Error("KEYWORD_IS_REQURED");
  }

  if (userName === keyword) {
    try {
      const userData = await fetchUserProfile(uid);
      return {
        name: userData.screen_name,
        avatar: userData.profile_image_url,
        // avatar_large: userData.avatar_large,
        // avatar_hd: userData.avatar_hd,
        id: userData.id,
        followers_count: userData.followers_count,
        friends_count: userData.friends_count,
        url: userData.url,
      };
    } catch (error) {
      throw error;
    }
  } else {
    throw new Error("USER_DOES_NOT_EXIST");
  }
};

const parseWeiboResponse = (html) => {
  // 解析 HTML
  const $ = cheerio.load(html);
  const weibos = [];
  $(".card-wrap").each((i, elem) => {
    const weibo = {
      content: $(elem).find(".name").text(),
      // 添加更多微博内容的提取逻辑
    };
    weibos.push(weibo);
  });

  return weibos;
};

//-----------------------------------------微博发布作品开始----------------------------------------------------
const publish = async (params) => {
  const browser = await puppeteer.launch({
    headless: "new",
    headless: false,
    userDataDir,
    executablePath,
    defaultViewport: null,
    args: [
      "--no-sandbox",
      "--disable-setuid-sandbox",
      "--disable-features=site-per-process",
      "--start-maximized",
      // "--auto-open-devtools-for-tabs",
    ],
    ignoreHTTPSErrors: true,
    // 忽略默认参数 --enable-automation, 防止被检测到是自动化测试
    ignoreDefaultArgs: ["--enable-automation"],
  });
  const page = await browser.newPage();
  // 设置 userAgent, 防止被检测到是自动化测试
  await page.setUserAgent(process.env.USER_AGENT);
  //根据屏幕尺寸设置页面大小
  const { width, height } = await page.evaluate(() => {
    return {
      width: document.documentElement.clientWidth,
      height: document.documentElement.clientHeight,
    };
  });
  logger.info(
    "浏览器窗口实际大小: " + JSON.stringify({ width, height }, null, 2)
  );
  await page.setViewport({ width, height });
  try {
    await page.goto("https://weibo.com/manage/manage", {
      waitUntil: "networkidle2",
    });
    if (await isNotLogin(page)) {
      logger.info("未登录");
      await notification(
        "微博",
        `${process.env.NODE_ENV}环境下的微博未登录`,
        "请扫码登录"
      );

      // 显示二维码
      await showQRCode(page);

      // 等待用户登录
      await waitForUserLogin(page);

      await notification(
        "微博",
        `${process.env.NODE_ENV}环境下的微博登录成功`,
        "登录成功"
      );
    }
    if (params.content_type === "video") {
      logger.info("发布视频");
      const result = await publishVideo(page, params);
      return result;
    } else if (params.content_type === "news") {
      const result = await publishNews(page, params);
      logger.info("发布图文");
      return result;
    } else {
      logger.error("不支持的内容类型");
      return {
        message: "不支持的内容类型",
        success: false,
      };
    }
  } catch (error) {
    logger.error(`发生错误: ${JSON.stringify(error, null, 2)}`);
    return {
      message: error.message,
      success: false,
    };
  } finally {
    await browser.close();
  }
};
//发布视频
async function publishVideo(page, params) {
  try {
    await page.goto("https://weibo.com/upload/channel");

    // 下载文件
    params = await downloadFiles(params);

    // 等待视频上传按钮出现
    await page.waitForSelector("button[id*='video_button_upload_']");

    // 使用 waitForFileChooser 和 click 的组合来处理文件选择
    const [fileChooser] = await Promise.all([
      page.waitForFileChooser(),
      page.click("button[id*='video_button_upload_']"),
    ]);

    // 接受文件选择并上传视频
    await fileChooser.accept([params.video]);
    // 等待上传完成的指示器
    await page.waitForSelector("div[class*='VideoUpload_info_']:last-child", {
      visible: true,
    });
    logger.info("视频上传成功");
    await new Promise((resolve) => setTimeout(resolve, 1500));
    // 如果有封面图，上传封面图
    if (params.cover) {
      // 点击修改封面按钮
      await page.waitForSelector('div[class*="Picture_box_"] a');
      // 使用 waitForFileChooser 和 click 的组合来处理文件选择
      const [fileChooser] = await Promise.all([
        page.waitForFileChooser(),
        page.click('div[class*="Picture_box_"] a'),
      ]);
      // 接受文件选择并上传视频
      await fileChooser.accept([params.cover]);
      // 等待封面上传完成
      logger.info("本地封面选择成功");
      await new Promise((resolve) => setTimeout(resolve, 1500));
      // 点击完成按钮
      await page.evaluate(() => {
        const buttons = document.querySelectorAll(
          'div[class*="VideoEdit_layer_"] button'
        );
        Array.from(buttons).forEach((item) => {
          if (item.textContent.includes("完成")) {
            item.click();
          }
        });
      });
      await page.waitForSelector('div[class*="VideoEdit_layer_"]', {
        visible: false,
      });
      logger.info(`本地封面上传成功`);
    }

    // 输入标题
    if (params.title) {
      await page.waitForSelector('input[placeholder*="标题"]');
      await page.evaluate((title) => {
        const input = document.querySelector('input[placeholder*="标题"]');
        input.value = title;
        input.dispatchEvent(new Event("input", { bubbles: true }));
      }, params.title);
      logger.info(`标题: ${params.title}`);
      await new Promise((resolve) => setTimeout(resolve, 1000));
    }
    // 输入正文
    const contentInput = await page.waitForSelector(
      'textarea[class*="Form_input_"]'
    );
    await contentInput.type(params.summary);
    logger.info(`正文: ${params.summary}`);
    await new Promise((resolve) => setTimeout(resolve, 1000));
    // 添加话题
    if (params.talk && params.talk.length > 0) {
      for (const topic of params.talk) {
        await contentInput.type(`#`, { delay: 100 });
        await new Promise((resolve) => setTimeout(resolve, 1000));
        // 直接设置输入值并触发必要的事件
        await contentInput.type(topic, { delay: 100 });
        await page.evaluate(() => {
          const input = document.querySelector(
            'textarea[class*="Form_input_"]'
          );
          // 触发一系列事件来模拟真实输入
          const events = ["input", "keydown", "keypress", "keyup", "change"];
          events.forEach((eventType) => {
            input.dispatchEvent(new Event(eventType, { bubbles: true }));
          });
        });
        await new Promise((resolve) => setTimeout(resolve, 2000));
        await page.keyboard.press("Enter");
        logger.info(`添加话题: ${topic}`);
        await new Promise((resolve) => setTimeout(resolve, 2000));
      }
    }
    // 添加@用户
    if (params.at_users && params.at_users.length > 0) {
      for (const user of params.at_users) {
        await contentInput.type(`@`, { delay: 100 });
        await contentInput.type(`${user}`, { delay: 100 });
        await page.keyboard.press("Space");
        logger.info(`添加@用户: ${user}`);
        await new Promise((resolve) => setTimeout(resolve, 2000));
      }
    }
    // 设置类型
    if (params.type !== undefined && params.type !== "") {
      logger.info(`设置类型: ${params.type}`);
      const typeObj = {
        0: "原创",
        1: "二创",
        2: "转载",
      };
      logger.info(`设置类型: ${typeObj[params.type]}`);
      await page.evaluate((type) => {
        const radios = document.querySelectorAll(
          'div[class*="Type_switch_"] label'
        );
        Array.from(radios).forEach((item) => {
          if (item.textContent.includes(type)) {
            item.click();
          }
        });
      }, typeObj[params.type]);
      await new Promise((resolve) => setTimeout(resolve, 1000));
    }
    // 作者声明
    if (params.author_statement && params.author_statement != 9999) {
      await handleAuthorStatement(page, params.author_statement);
      await new Promise((resolve) => setTimeout(resolve, 1000));
    }
    // 可见范围
    if (params.permission) {
      await handlePermission(page, params.permission);
    }
    await new Promise((resolve) => setTimeout(resolve, 1500));
    // 点击发布
    await page.click('div[class*="Tool_check_"] button');
    // 等待发布完成
    const response = await page.waitForResponse((response) =>
      response.url().includes("https://weibo.com/ajax/statuses/update")
    );
    const responseData = await response.json();
    //#TAG: 微博视频发布，缺少id字段(跟产品后端沟通，传空字符串即可)
    if (responseData.ok === 1) {
      logger.info("发布视频成功");
      return {
        id: responseData.data.mid || "",
        message: responseData.msg,
        success: true,
      };
    } else {
      logger.error("发布视频失败");
      return {
        message: responseData.msg,
        success: false,
      };
    }
  } catch (error) {
    logger.error(`发布视频失败: ${error.message}`);
    return {
      message: error.message,
      success: false,
    };
  }
}
// 发布图文
async function publishNews(page, params) {
  await page.goto("https://weibo.com/");
  // 下载文件
  params = await downloadFiles(params);
  const fileInput = await page.waitForSelector(
    'input[class*="FileUpload_file_"][type="file"]'
  );
  // 批量上传
  await fileInput.uploadFile(...params.images);
  // 等待 所有https://picupload.weibo.com/interface/upload.php的请求都结束，证明上传成功
  // 创建一个 Promise 来等待所有上传完成
  const waitForAllUploads = new Promise((resolve, reject) => {
    let uploadCount = 0;
    const totalUploads = params.images.length;

    const checkAllUploadsComplete = () => {
      if (uploadCount === totalUploads) {
        resolve();
      }
    };

    page.on("response", async (response) => {
      if (
        response
          .url()
          .includes("https://picupload.weibo.com/interface/upload.php")
      ) {
        uploadCount++;
        logger.info(`图片上传进度: ${uploadCount}/${totalUploads}`);
        checkAllUploadsComplete();
      }
    });

    // 设置超时
    setTimeout(() => {
      reject(new Error("图片上传超时"));
    }, 600000); // 600秒超时
  });
  try {
    await waitForAllUploads;
    logger.info("所有图片上传成功");
    // 输入内容
    const inputSelector = 'textarea[placeholder*="有什么新鲜事想分享给大家"]';
    await page.waitForSelector(inputSelector);
    // 清空之前的内容
    await page.evaluate((selector) => {
      const input = document.querySelector(selector);
      input.value = "";
      input.dispatchEvent(new Event("input", { bubbles: true }));
    }, inputSelector);
    await new Promise((resolve) => setTimeout(resolve, 1000));
    await page.type(inputSelector, params.summary);
    // 等待一小段时间，确保内容已经更新
    await new Promise((resolve) => setTimeout(resolve, 1000));
    logger.info(`正文: ${params.summary}`);
    // 添加话题
    await handleTalk(page, params.talk, inputSelector);
    // @用户
    await handleAt(page, params.at_users, inputSelector);
    // 作者声明
    await handleAuthorStatement(page, params.author_statement);
    // 可见范围
    await handlePermission(page, params.permission);
    await new Promise((resolve) => setTimeout(resolve, 1500));
    // 点击发布
    await page.click('div[class*="Tool_check_"] button');
    // 等待发布完成
    const response = await page.waitForResponse((response) =>
      response.url().includes("https://weibo.com/ajax/statuses/update")
    );
    const responseData = await response.json();
    if (responseData.ok === 1) {
      logger.info("发布图文成功");
      return {
        id: responseData.data.mid || "",
        message: responseData.msg,
        success: true,
      };
    } else {
      logger.error("发布图文失败");
      return {
        message: responseData.msg,
        success: false,
      };
    }
  } catch (error) {
    logger.error(`发布图文失败: ${error.message}`);
    return {
      message: error.message,
      success: false,
    };
  }
}
// 添加话题
async function handleTalk(page, talk, inputSelector) {
  if (talk && talk.length > 0) {
    logger.info(`添加话题: ${talk}`);
    for (const topic of talk) {
      await page.type(inputSelector, `#`, { delay: 100 });
      await new Promise((resolve) => setTimeout(resolve, 1500));
      await page.type(inputSelector, `${topic}`, { delay: 100 });
      await page.evaluate((selector) => {
        const input = document.querySelector(selector);
        // 触发一系列事件来模拟真实输入
        const events = ["input", "keydown", "keypress", "keyup", "change"];
        events.forEach((eventType) => {
          input.dispatchEvent(new Event(eventType, { bubbles: true }));
        });
      }, inputSelector);
      await new Promise((resolve) => setTimeout(resolve, 2000));
      await page.keyboard.press("Enter");
      logger.info(`添加话题完成`);
      await new Promise((resolve) => setTimeout(resolve, 1000));
    }
  }
}
// @用户
async function handleAt(page, at, inputSelector) {
  if (at && at.length > 0) {
    logger.info(`添加@用户: ${at}`);
    for (const user of at) {
      await page.type(inputSelector, `@`, { delay: 100 });
      await new Promise((resolve) => setTimeout(resolve, 1500));
      await page.type(inputSelector, `${user}`, { delay: 100 });
      await new Promise((resolve) => setTimeout(resolve, 2000));
      await page.keyboard.press("Space");
      logger.info(`添加@用户完成`);
      await new Promise((resolve) => setTimeout(resolve, 1000));
    }
  }
}
// 作者声明
async function handleAuthorStatement(page, authorStatement) {
  if (authorStatement) {
    logger.info(`添加作者声明: ${authorStatement}`);
    await page.click('div[class*="Visible_text"]');
    await page.waitForSelector('div[class*="Visible_pop2_"]', {
      visible: true,
    });
    await page.click('div[class*="Visible_spe1_"]');
    await page.waitForSelector('div[class*="Visible_popc_"]', {
      visible: true,
    });
    await page.evaluate((stateMent) => {
      const allBtns = document.querySelectorAll(
        'div[class*="Visible_con_"] button'
      );
      Array.from(allBtns).forEach((item, index) => {
        if (index == stateMent) {
          item.click();
        }
      });
    }, authorStatement);
    logger.info(`添加作者声明完成: ${authorStatement}`);
    await new Promise((resolve) => setTimeout(resolve, 1000));
  }
}
// 可见范围
async function handlePermission(page, permission) {
  if (permission) {
    logger.info(`添加可见范围: ${permission}`);
    const permissionObj = {
      1: "公开",
      2: "仅自己可见",
      3: "粉丝",
      4: "好友圈",
    };
    await page.click('div[class*="Visible_text"]');
    await page.waitForSelector('div[class*="Visible_pop2_"]', {
      visible: true,
    });
    await page.evaluate((permission) => {
      const allBtns = document.querySelectorAll(
        'div[class*="Visible_pop2_"] div[role="button"]'
      );
      Array.from(allBtns).forEach((item) => {
        if (item.textContent.includes(permission)) {
          item.click();
        }
      });
    }, permissionObj[permission]);
    logger.info(`添加可见范围完成: ${permissionObj[permission]}`);
    await new Promise((resolve) => setTimeout(resolve, 1000));
  }
}
//下载文件
async function downloadFiles(params) {
  logger.info(`开始下载文件，内容：${params.summary}`);
  const date = dayjs().format("YYYY-MM-DD");
  const dir = path.join(__dirname, `../uploads/weibo/${date}`);
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true });
  }

  const downloadPromises = [];

  // 处理视频
  if (params.video) {
    const videoName = path.basename(new URL(params.video).pathname);
    const videoPath = path.join(dir, videoName);
    downloadPromises.push(
      downloadFile(params.video, videoPath).then(() => {
        params.video = videoPath;
        logger.info(`视频下载成功，地址：${videoPath}`);
      })
    );
  }

  // 处理图片列表
  if (params.images) {
    const images = Array.isArray(params.images)
      ? params.images
      : JSON.parse(params.images);
    params.images = await Promise.all(
      images.map(async (imageUrl, index) => {
        const imageName = `image_${index}${path.extname(new URL(imageUrl).pathname) || ".jpg"
          }`;
        const imagePath = path.join(dir, imageName);
        await downloadFile(imageUrl, imagePath);
        logger.info(`图片下载成功，地址：${imagePath}`);
        return imagePath;
      })
    );
  }

  // 处理封面
  if (params.cover) {
    const coverUrl = Array.isArray(params.cover)
      ? params.cover[0]
      : params.cover;
    const coverName = path.basename(new URL(coverUrl).pathname);
    const coverPath = path.join(dir, coverName);
    await downloadFile(coverUrl, coverPath);
    params.cover = coverPath;
    logger.info(`封面下载成功，地址：${coverPath}`);
  }

  await Promise.all(downloadPromises);
  logger.info(`所有文件下载完成`);
  return params;
}
//下载文件
async function downloadFile(fileUrl, localPath) {
  logger.info(`开始下载文件，地址：${fileUrl}`);

  const response = await axios({
    method: "GET",
    url: fileUrl,
    responseType: "stream",
  });

  await pipeline(response.data, fs.createWriteStream(localPath));
}
//-----------------------------------------微博发布作品结束----------------------------------------------------
